// import { JPush } from "@jiguang-ionic/jpush";
import { ImgInfoPage } from "./../img-info/img-info";

/**
 * Generated class for the RcmdPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */
import {
  Component,
  Injector,
  ElementRef,
  ViewChild,
  ChangeDetectorRef
} from "@angular/core";
import { Tabs, Content } from "ionic-angular";
import { IonicPage, App } from "ionic-angular";
import { StorageService } from "../../providers/StorageService";
import { UserPosVo } from "../../model/UserPosVo";
import { BasePage } from "../basePage";
import { Events } from "ionic-angular";
import { StyleService } from "../../providers/StyleService";
import { PIC_URL, PAGE_SIZE } from "../../providers//Config";
import { TweenMax } from "gsap";
import {
  ThemeableBrowser,
  ThemeableBrowserOptions,
  ThemeableBrowserObject
} from "@ionic-native/themeable-browser";

declare var $: any;

@IonicPage()
@Component({
  selector: "page-rcmd",
  templateUrl: "rcmd.html",
  providers: [StyleService]
})
export class RcmdPage extends BasePage {
  ids: "";
  oboaut = "0";
  picrooturl = ""; //图片服务器地址
  @ViewChild("rcmdContainer") content: Content;
  adList = [];
  //前7款
  styleList = [];
  //剩下弹出的款式
  otherStyleList = [];
  popAdObj = [];
  picUrl = PIC_URL;
  currCity = "北京";
  userPosVo = {};
  /**
   * 分页组件对象
   */
  private pagingObj: any;
  //当前页码
  private page = 0;
  //当前list 的数组
  styleMore = [];
  //上一个点击的类目
  previousItem: any;
  //默认选中第一项
  private isFristStyle: boolean = true;
  cateItemDiv: ElementRef;
  _elementRef: any;
  //是否显示回到顶部
  public showButton = false;

  //滚动到顶的按钮
  private scrBtn;
  /**
   * 当前选中的styleId
   */
  private styleId;
  picture = "";

  currBtnID = "";
  data4 = {
    user_id: "",
    nail_id: ""
  };
  top: boolean;
  msg: "";
  userinfo: any;
  hasdianzang: Number; /*用来记录是否执行了点赞操作*/

  //用来导航头定位
  fixed: boolean = false;

  /*获取首页信息的 要串乡后台的数据*/
  /*
  page_size	可选	int	获取数据长度 默认8
  page_pos	可选	int	获取数据起始点 默认0
  nail_type	可选	int	需要获取哪一款美甲款式 默认是1
  user_id	  可选	int	用于判断该用户是否点赞
  page_buy	可选	int	合作美店的分页
  bar_type	可选	int	不传:推荐 1:最新 2:热门
  user_id   可选    没有登录就不传
  */

  paramForgetStyleByid = {
    page_size: null,
    page_pos: 0,
    nail_type: 1,
    user_id: null,
    page_buy: null,
    bar_type: null
  };

  myEvent;
  constructor(
    injector: Injector,
    stgSc: StorageService,
    public appCtrl: App,
    public events: Events,
    private themeableBrowser: ThemeableBrowser,
    public styleProvider: StyleService,
    public stc: StorageService,
    private cd: ChangeDetectorRef,
    // public jpush: JPush
  ) {
    super(injector);
    this.picture = PIC_URL;
    this.userinfo = this.stc.read("userinfo");
    this.events.subscribe("user:created", (res, time) => {
      RcmdPage.prototype.myEvent = res;
      console.log(RcmdPage.prototype.myEvent);
      this.recommend(res);
    });
    
    // let openNotification = this.jpush.openNotification()  
    // .subscribe( res => {  
    //   console.log(res);  
    //   console.log('收到点击通知事件')  
    // })  


  // let receiveNotification = this.jpush.receiveNotification()  
  //   .subscribe( res => {  
  //     console.log(res)  
  //     console.log('收到通知')  
  //   })  

  // let receiveMessage = this.jpush.receiveMessage()  
  //   .subscribe( res => {  
  //     console.log(res)  
  //     console.log('收到自定义消息')  
  //   })  

  // let backgroundNotification = this.jpush.backgroundNotification()  
  //   .subscribe( res => {  
  //     console.log(res)  
  //     console.log('收到后台通知')  
  //   })  
  }

  //只调用一次
  // ionViewDidLoad = () => {
  //   this.adList = this.navCtrl.parent._views[0].instance.adList;
  //   this.showLoading();
  //   //取款式列表
  //   this.styleProvider.getStyleList().then(
  //     (res) => {
  //       this.closeLoading();
  //       if (res) {
  //         if (res.error_code == 0) {
  //           let allStyleList = res.data;
  //           this.currBtnID = allStyleList[0].id;
  //           //以 plus6 为基准 ，截7个，最后一个为 更多
  //           this.styleList = allStyleList.slice(0, 7);
  //           this.otherStyleList = allStyleList.slice(7);

  //           this.otherStyleList.forEach(element => {
  //             element['selected'] = false;
  //           });
  //           //为 home 赋值
  //           this.navCtrl.parent._views[0].instance.otherStyleList = this.otherStyleList;
  //           //滚动按钮
  //           this.scrBtn = document.getElementById("scrollTop");
  //           this.styleList.push({ id: "1000", type_name: "更多款" });
  //           var timeId = setTimeout(() => {
  //             var firstChild = $(".btn_cls:first")[0];//用选择器的方式获取第一个子元素

  //             this.scrBtn = document.getElementById("scrollTop");
  //             this.styleItemClick(firstChild, null, this.styleList[0]);
  //             clearTimeout(timeId);
  //           }, 10)
  //         }
  //         else
  //           this.showAlert(res.msg)
  //       }
  //     })
  // }

  //每次调用

  ngAfterViewInit() {
    this.content.ionScroll.subscribe(() => {
      if (this.content.scrollTop >= 200) {
        this.fixed = true;
      } else if (this.content.scrollTop <= 220) {
        this.fixed = false;
      }
    });
    // this.jpush.init().then(res => {
    //   alert(res);
    // });
    // this.jpush.isPushStopped().then(callback => {
    //   alert(callback);
    // });
    // this.jpush.getRegistrationID().then(rId => {
    //   alert(rId);
    // });
    // // document.addEventListener('jpush.receiveRegistrationId', function (event) {
    // //   console.log(event.registrationId)
    // // }, false)
    // this.jpush.setAlias({ sequence: 1, alias: "your_alias" }).then(
    //   result => {
    //     var sequence = 1;
    //     var alias = "your_alias";
    //   },
    //   error => {
    //     var sequence = error.sequence;
    //     var errorCode = error.code;
    //   }
    // );
  
  }

  // init() {  
  //   this.jpush.init()  
  //   .then(res => alert(res))  
  //   .catch(err => alert(err))  
  //   }  

  //   getRegistrationID() {  
  //     this.jpush.getRegistrationID()  
  //     .then(res => alert(res))  
  //     .catch(err => alert(err))  
  //     }  

  ionViewDidLoad() {
    let res2 = this.navParams.get("res");
    this.paramForgetStyleByid.page_size = PAGE_SIZE;
    if (this.userinfo != null) {
      this.paramForgetStyleByid.user_id = this.userinfo.user_id;
    }
    console.log(this.paramForgetStyleByid);
    console.log(res2);
    this.doRefresh(event);
    // this. init()
  }

  ionViewDidEnter() {
    document.title = "精选";
    // let stxt = document.querySelector(".searchbar-input");
    // stxt["disabled"] = true;
    // this.__refreshActive = true;
    // this.refreshing.complete
  }

  //打开右侧菜单
  openMenu() {
    // this.menuCtrl.open('left');
    console.log("打开右侧菜单");
    this.menuCtrl.enable(true, "notDetail");
    this.menuCtrl.enable(false, "isDetail");
    this.menuCtrl.open();
    //  console.log("成功打开右侧菜单");
  }

  toTop() {
    this.content.scrollTo(0, 0, 300);
  }
  open() {
    this.menuCtrl.open();
  }
  //选择了首页某个大模块
  selectFunc(funcName) {}

  styleItemClick = (
    itemObj: any = null,
    event: MouseEvent = null,
    item = null,
    idx = 0
  ) => {
    let oldTxt = this.previousItem ? this.previousItem.innerText : "";
    let currItem = itemObj._elementRef
      ? itemObj._elementRef.nativeElement
      : itemObj;
    if (oldTxt == currItem.innerText && idx < 7) {
      // 更多款式时，可以一直点
      return;
    }
    this.showButton = false;
    if (this.previousItem) {
      this.previousItem.style["background-color"] = "rgba(255, 255, 255, 0.43)";
      this.previousItem.style["color"] = "#fd6186";
      oldTxt = this.previousItem.innerText;
    }

    currItem.style["background-color"] = "#fd6186";
    currItem.style["color"] = "#ffffff";
    this.previousItem = currItem;

    if (item) {
      this.styleId = item.id;
      if (item.id == "1000") this.openMenu();
      else {
        //取此款式下具体的明细样式

        this.getStyleDetail(item.id);
        // this.starId = this.categoryArr[0].id;
      }
      //this.starId = item.id;
    }
  };

  //选中了某个款式
  showMoreStyle = item => {
    //alert(item.id);
    this.otherStyleList.forEach(element => {
      element["selected"] = false;
    });
    item.selected = true;
    this.menuCtrl.close();
    this.previousItem.innerText = item.type_name;
    this.styleId = item.id;
    this.getStyleDetail(item.id);
  };

  /**
   * 得到某款式的明细样式
   * @param id
   */
  async getStyleDetail(id) {
    //如果是第一列
    if (this["page1_" + id]) {
      this.styleMore = this["page1_" + id];
      return;
    }
    this.page = 0;
    // let param;

    // if(this.userinfo===null){
    //   param = {  //未读页码
    //     page_size: PAGE_SIZE,
    //     page_pos: this['page'],
    //     nail_type: this.styleId,
    //   }
    // }else{
    //   param = {  //未读页码
    //     page_size: PAGE_SIZE,
    //     page_pos: this['page'],
    //     nail_type: this.styleId,
    //     user_id:this.userinfo.user_id
    //   }
    // }
    this.paramForgetStyleByid.page_pos = this["page"];
    this.paramForgetStyleByid.nail_type = this.styleId;
    console.log(this.paramForgetStyleByid);
    console.log("向后台请求的数据得到某款式的明细样式");
    this["page1_" + id] = await this.styleProvider.getStyleByid(
      this.paramForgetStyleByid
    );
    this["page1_" + id] = this["page1_" + id].data;
    this.styleMore = this["page1_" + id];
  }

  // export class PageOne {
  //   items: string[];

  //   constructor(private mockProvider: MockProvider) {
  //     this.items = mockProvider.getData();
  //   }

  //   doRefresh(refresher: Refresher) {
  //     console.log('DOREFRESH', refresher);

  //     this.mockProvider.getAsyncData().then((newData) => {
  //       for (var i = 0; i < newData.length; i++) {
  //         this.items.unshift( newData[i] );
  //       }

  //       refresher.complete();
  //     });
  //   }

  //   doPulling(refresher: Refresher) {
  //     console.log('DOPULLING', refresher.progress);
  //   }
  // }

  // doRefresh(refresher) {
  //   console.log('Begin async operation', refresher);

  //   setTimeout(() => {
  //     console.log('Async operation has ended');
  //     refresher.complete();
  //   }, 2000);
  // }
  /** 顶部刷新 */
  async doRefresh(refresher) {
    // refresher.complete();
    console.log(refresher);
    // this.pagingObj = refresher;
    this.page = 0;
    this.styleMore = [];

    // this.paramForgetStyleByid.page_buy = 0;
    if (this["page1_" + this.styleId]) {
      this.styleMore = this["page1_" + this.styleId];
      refresher.complete();
      return;
    }

    let res = await this.styleProvider.getStyleByid(this.paramForgetStyleByid);

    // console.log("请求回来的数据")
    console.log(res);

    if (res == undefined) {
      console.log("数据为空");
    } else {
      this.styleMore = this.styleMore.concat(res.data);
      console.log(this.styleMore);
      console.log(this.ids);
    }

    if (refresher) {
      refresher.complete();
    }
  }

  /**
   * 加载更多商品
   *
   * @param infiniteScroll
   */
  async doInfinite(infiniteScroll) {
    this.pagingObj = infiniteScroll;
    //page0 /page1 页码+1
    console.log(this.pagingObj);
    this.page = this.page + 1;
    //  let param = {  //未读页码
    // //   user_id: this.userinfo.user_id,
    //   page_size: PAGE_SIZE,
    //   page_pos: this['page'],
    //   nail_type: this.styleId,
    //   page_buy: 0,
    //   bar_type: this.ids
    // }
    this.paramForgetStyleByid.page_pos = this["page"];
    this.paramForgetStyleByid.nail_type = this.styleId;
    this.paramForgetStyleByid.page_buy = 0;
    this.paramForgetStyleByid.bar_type = this.ids;

    let res = await this.styleProvider.getStyleByid(this.paramForgetStyleByid);
    this["page1_" + this.styleId] = res.data;
    this.styleMore = this.styleMore.concat(res.data);
    console.log("开始加载更多数据");
    console.log(this.styleMore);
    this.pagingObj.complete();

    if (res.data.length == 0) {
      this.pagingObj.enable(false);
      return;
    }
    // this.doService(param);
  }

  /**
   * banner click
   * @param link
   */
  bannerClick(link) {
    const options: ThemeableBrowserOptions = {
      statusbar: {
        color: "#ffffffff"
      },
      toolbar: {
        height: 44,
        color: "#f0f0f0ff"
      },
      title: {
        color: "#003264ff",
        showPageTitle: true
      },
      backButton: {
        image: "back",
        imagePressed: "back_pressed",
        align: "left",
        event: "backPressed"
      },
      forwardButton: {
        image: "forward",
        imagePressed: "forward_pressed",
        align: "left",
        event: "forwardPressed"
      },
      closeButton: {
        image: "close",
        imagePressed: "close_pressed",
        align: "left",
        event: "closePressed"
      },
      customButtons: [
        {
          image: "share",
          imagePressed: "share_pressed",
          align: "right",
          event: "sharePressed"
        }
      ],
      backButtonCanClose: true
    };

    const browser: ThemeableBrowserObject = this.themeableBrowser.create(
      link,
      "_blank",
      options
    );
  }
  //显示滚动到顶部的按钮
  showScrollTopBtn() {
    if (this.content.scrollTop > window.innerHeight - 200) {
      if (this.showButton)
        //已经显示了　到顶按钮
        return;
      this.showButton = true;
      TweenMax.fromTo(
        this.scrBtn,
        0.5,
        { css: { alpha: 0, display: "block" } },
        { css: { alpha: 1 } }
      );
      console.log("显示到顶");
    } else {
      if (!this.showButton)
        //已经显示了　到顶按钮
        return;
      this.showButton = false;
      TweenMax.fromTo(
        this.scrBtn,
        0.5,
        { css: { alpha: 1 } },
        { css: { alpha: 0, display: "none" } }
      );
      console.log("隐藏到顶");
    }
    alert("滚动完了");
  }

  //滚动到顶
  scrollToTop() {
    if (this.content.isScrolling) {
      console.log("正在滚动");
      return;
    }
    this.content.scrollToTop();
  }
  /** 跳转美甲款式详情 */
  showGoodsDetail($event, i) {
    let tar = $event.target;
    console.dir(tar.parentElement.className);
    /*得到是否点击的是点赞图片*/
    let tarName = tar.parentElement.className;
    if (tarName != "ml1") {
      let modal = this.modalCtrl.create("ImgInfoPage", {
        id: this.styleMore[i].nail_id
      });
      modal.present();
    }
    // this.navCtrl.push("ImgInfoPage")
    //console.log(this.styleMore[i].nail_id)
    //this.appCtrl.getRootNavById('N4').push('ImgInfoPage',)
  }
  /** 点赞 */
  obout(nail_id, index) {
    console.log("开始点赞");
    console.log(nail_id, index);

    if (this.userinfo == null) return;

    this.data4.nail_id = nail_id;

    this.styleMore[index].hasdianzang = 1;
    this.zankNailAPI();
    if (this.styleMore[index].is_zank == 0) {
      this.styleMore[index].is_zank = 1;
      // this.doRefresh(this.pagingObj);
    } else {
      this.styleMore[index].is_zank = 0;
    }

    console.log("点赞结束");

    setTimeout(() => {
      this.hasdianzang = 0;
      console.log((this.styleMore[index].hasdianzang = 0));
    }, 400);
  }
  /** 推荐 */
  recommend(id) {
    console.log(id);
    this.ids = id;
    $(".btn").removeClass("active");
    $(".btn")
      .eq(id)
      .addClass("active");
    this.doRefresh(id);
  }

  /** 跳转款式 */
  add() {
    // this.navCtrl.push("AddLabelPage");
    let modal = this.modalCtrl.create("AddLabelPage");
    modal.present();
  }

  /** 点赞操作 */
  async zankNailAPI() {
    console.log();
    if (this.userinfo == null) {
      this.showAlert("您当前未登录，请登录后操作！");
    } else {
      this.data4.user_id = this.userinfo.user_id;
      console.log(this.data4);
      let res = await this.styleProvider.zankNailAPI(this.data4);
      console.log(res);
      if (res.error_code == 0) {
        this.msg = res.msg;
        this.presentToast();
      } else if (res.error_code == 1001) {
        this.msg = res.reason;
        this.presentToast();
        return;
      }
    }
  }
  /** 提示 */
  presentToast() {
    let toast = this.toastCtrl.create({
      message: this.msg,
      duration: 2000,
      position: "top"
    });
    toast.onDidDismiss(() => {
      console.log("Dismissed toast");
    });

    toast.present();
  }
  //跳转到美甲师详情
  gotoNailer() {
    let modal = this.modalCtrl.create("NailerDetailPage");
    modal.present();
  }
}
